package com.heyxampis.newmantis.util.utilitarios;

import java.io.File;
import java.text.Normalizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.activation.MimetypesFileTypeMap;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Utils { // NOPMD by Junior on 23/03/13 17:19

	private static final Log LOG = LogFactory.getLog(Utils.class);

	public static HttpSession requestSession() {
		HttpSession session = null;
		try {
			final FacesContext facesContext = FacesContext.getCurrentInstance();
			session = (HttpSession) facesContext.getExternalContext()
					.getSession(false);

			if (session == null) {
				session = (HttpSession) facesContext.getExternalContext()
						.getSession(true);
			}

		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return session;
	}

	public static String soNumeros(final String string) {
		String stringFormatada = null;
		try {
			stringFormatada = string.replaceAll("[^0-9]", "");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return stringFormatada;
	}

	public static boolean validarEmail(final String email) {
		boolean isValid = false;

		try {
			if (StringUtils.isNotBlank(email)) {
				final Pattern p = Pattern
						.compile("^[\\w-]+(\\.[\\w-]+)*@([\\w-]+\\.)+[a-zA-Z]{2,7}$");
				final Matcher m = p.matcher(email);

				if (m.find()) {
					isValid = true;
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}

		return isValid;
	}

	public static String getMimeType(final String nomeArquivo) {
		final File file = new File(nomeArquivo);
		return new MimetypesFileTypeMap().getContentType(file);
	}

	public static String getExtensao(final String nomeArquivo) {
		final String extensao = nomeArquivo.substring(
				nomeArquivo.lastIndexOf("."), nomeArquivo.length()); // NOPMD by Junior on 23/03/13 17:19
		return extensao.substring(1, 4);
	}

	public static String removerAcentos(final String string) {
		String texto = string;
		texto = Normalizer.normalize(texto, Normalizer.Form.NFD);
		texto = texto.replaceAll("[^\\p{ASCII}]", "");
		return texto;
	}

}
